package com.weipu.common.facade.content.api;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import android.content.ContentValues;
import android.database.Cursor;

import com.weipu.common.DXApplication;
import com.weipu.common.facade.content.BaseService;
import com.weipu.common.facade.content.ContentURI;
import com.weipu.common.facade.content.colum.ProductColumn;
import com.weipu.common.facade.model.ProductModel;
import com.weipu.common.util.Logger;

/**
 * 产品数据操作接口封装
 * 
 * @author zhl014
 */
public class ProductService extends BaseService
{
    
    private static final String TAG = "ProductService";
    public static final String TYPE_BFD_HOME = "type_bfd_home";
    public static final String TYPE_BFD_SEARCH = "type_bfd_search";
    public static final String TYPE_BFD_PAY = "type_bfd_pay";
    
    /**
     * 保存产品信息(异步)
     * 
     * @param product
     * @param type
     *            产品信息对象{@link ProductModel}
     * 
     */
    public boolean saveProductInfo(ProductModel product, String type)
    {
        if (Logger.isLog)
        {
            Logger.d("saveProductInfo(ProductModel) - start, product: "
                + (null == product ? "null" : product.getShortHeadLine1()) + ", type: " + type);
        }
        
        ContentValues initialValues = new ContentValues();
        // Model与values转换
        initialValues.put(ProductColumn.CURRENCY_CODE, product.getCurrencyCode());
        initialValues.put(ProductColumn.ENTITY_ID, product.getEntityID());
        initialValues.put(ProductColumn.FREE_SHIPPING, product.getFreeShipping());
        initialValues.put(ProductColumn.INTRODUCTION, product.getIntroduction());
        initialValues.put(ProductColumn.LANGUAGE, product.getLanguage());
        initialValues.put(ProductColumn.LISTP_RICE, product.getListprice());
        initialValues.put(ProductColumn.PHOTOS_COUNT, product.getPhotosCount());
        
        if (null != product.getBigPictureURL() && product.getBigPictureURL().length > 0)
        {
            initialValues.put(ProductColumn.PIC_BIG_URL, writeStream(product.getBigPictureURL()));
        }
        
        if (null != product.getMediumPictureURL() && product.getMediumPictureURL().length > 0)
        {
            initialValues.put(ProductColumn.PIC_MEDIUM_URL, writeStream(product.getMediumPictureURL()));
        }
        
        if (null != product.getSmallPictureURL() && product.getSmallPictureURL().length > 0)
        {
            initialValues.put(ProductColumn.PIC_SMALL_URL, writeStream(product.getSmallPictureURL()));
        }
        
        initialValues.put(ProductColumn.PRICE, product.getPrice());
        initialValues.put(ProductColumn.PRODUCT_NAME, product.getShortHeadLine1());
        initialValues.put(ProductColumn.PRODUCT_RATING, product.getProductRating());
        
        if (null != product.getRelateFreeShipping() && product.getRelateFreeShipping().length > 0)
        {
            initialValues.put(ProductColumn.RELATE_FREE_SHIPPING, writeStream(product.getRelateFreeShipping()));
        }
        
        initialValues.put(ProductColumn.REVIEW_COUNT, product.getReviewCount());
        initialValues.put(ProductColumn.SKU, product.getSku());
        initialValues.put(ProductColumn.SPECIFICATION, product.getSpec());
        initialValues.put(ProductColumn.TYPE, type);
        if (0 == product.getCacheUpdateTime())
        {
            initialValues.put(ProductColumn.UPDATE_TIME, System.currentTimeMillis());
        }
        else
        {
            initialValues.put(ProductColumn.UPDATE_TIME, product.getCacheUpdateTime());
        }
        initialValues.put(ProductColumn.WEB_URL, product.getWebUrl());
        
        boolean isSuccess = false;
        
        try
        {
            DXApplication.getContext()
                .getContentResolver()
                .insert(ContentURI.ProductList.CONTENT_URI_ALL, initialValues);
            isSuccess = true;
            Logger.e(TAG, "saveProductInfo isSuccess");
        }
        catch (Exception e)
        {
            Logger.e(TAG, "saveProductInfo error.", e);
        }
        
        if (Logger.isLog)
        {
            Logger.d("saveProductInfo(ProductModel) - end, isSuccess: " + isSuccess);
        }
        return isSuccess;
    }
    
    /**
                 * 根据产品ID删除对应数据
     * 
     * @param sku
     *            产品ID
     */
    public int deleteProductInfoByID(String sku)
    {
        if (Logger.isLog)
        {
            Logger.d("deleteProductInfoByID(String) - start, sku: " + sku);
        }
        
        String selection = ProductColumn.SKU + "=?";
        String[] selectionArgs = {sku};
        
        int returnint =
            DXApplication.getContext()
                .getContentResolver()
                .delete(ContentURI.ProductList.CONTENT_URI_ALL, selection, selectionArgs);
        
        if (Logger.isLog)
        {
            Logger.d("deleteProductInfoByID(String) - end, sku: " + sku);
        }
        return returnint;
    }
    
    /**
                   * 根据产品分类删除子产品列表
     * 
     * @param type
     *            String
     */
    public int deleteProductListByType(String type)
    {
        if (Logger.isLog)
        {
            Logger.d("deleteProductListByParentID(String) - start, type: " + type);
        }
        
        String selection = ProductColumn.TYPE + "=?";
        String[] selectionArgs = {type};
        
        int returnint =
            DXApplication.getContext()
                .getContentResolver()
                .delete(ContentURI.ProductList.CONTENT_URI_ALL, selection, selectionArgs);
        if (Logger.isLog)
        {
            Logger.d("deleteProductListByParentID(String) - end,returnint: " + returnint);
        }
        return returnint;
    }
    
    /**
     * 删除所有产品数据
     * 
     */
    public int clearProduct()
    {
        if (Logger.isLog)
        {
            Logger.d("clearProduct() - start");
        }
        
        int returnint =
            DXApplication.getContext().getContentResolver().delete(ContentURI.ProductList.CONTENT_URI_ALL, null, null);
        
        if (Logger.isLog)
        {
            Logger.d("clearProduct() - end, returnint: " + returnint);
        }
        return returnint;
        
    }
    
    /**
                   * 查询产品信息对象(异步) 如果存在多个则默认返回第一个(根据数据Row ID升序 )
     * 
     * @param sku
     */
    public ProductModel queryProductDetailByProductID(int sku)
    {
        if (Logger.isLog)
        {
            Logger.d("queryProductDetailByType(String) - start, sku: " + sku);
        }
        
        String[] projection = ProductColumn.QUERY_PROJECTION;
        
        String selection = ProductColumn.SKU + "=?";
        
        Cursor cursor = null;
        ProductModel returnProductModel = null;
        try
        {
            cursor =
                DXApplication.getContext()
                    .getContentResolver()
                    .query(ContentURI.ProductList.CONTENT_URI_ALL,
                        projection,
                        selection,
                        new String[] {String.valueOf(sku)},
                        null);
            returnProductModel = parseModel(cursor);
        }
        catch (Exception e)
        {
            Logger.e(TAG, "queryProductDetailByProductID error.", e);
        }
        finally
        {
            close(cursor);
        }
        
        if (Logger.isLog)
        {
            Logger.d("queryProductDetailByProductID(String) - end, returnProductModel: " + returnProductModel);
        }
        return returnProductModel;
    }
    
    /**
               * 查询指定类型下产品列表
     * 
     * @param type
     */
    public ArrayList<ProductModel> queryProductListByType(String type)
    {
        if (Logger.isLog)
        {
            Logger.d("queryProductListByType(String) - start, type: " + type);
        }
        
        String[] projection = ProductColumn.QUERY_PROJECTION;
        
        String selection = ProductColumn.TYPE + "=?";
        
        Cursor cursor = null;
        ArrayList<ProductModel> returnProductModel = null;
        try
        {
            cursor =
                DXApplication.getContext()
                    .getContentResolver()
                    .query(ContentURI.ProductList.CONTENT_URI_ALL, projection, selection, new String[] {type}, null);
            
            returnProductModel = parseModelList(cursor);
        }
        catch (Exception e)
        {
            Logger.e(TAG, "queryProductListByType error.", e);
        }
        finally
        {
            close(cursor);
        }
        
        if (Logger.isLog)
        {
            Logger.d("queryProductListByType(String) - end, returnProductModel: "
                + (null != returnProductModel ? returnProductModel.size() : "0"));
        }
        return returnProductModel;
    }
    
    // 解析产品对象
    private ProductModel parseModel(Cursor c)
    {
        
        if (null == c || c.getCount() < 1)
        {
            return null;
        }
        
        c.moveToFirst();
        
        ProductModel returnProductModel = getSingleModel(c);
        
        return returnProductModel;
    }
    
    private ProductModel getSingleModel(Cursor c)
    {
        
        //        public static final String[] QUERY_PROJECTION = {
        //            ProductColumn.CURRENCY_CODE,  0
        //            ProductColumn.ENTITY_ID,
        //            ProductColumn.FREE_SHIPPING,
        //            ProductColumn.INTRODUCTION,
        //            ProductColumn.LANGUAGE, 
        //            ProductColumn.LISTP_RICE,
        //            ProductColumn.PHOTOS_COUNT,
        //            ProductColumn.PIC_BIG_URL,
        //            ProductColumn.PIC_MEDIUM_URL,
        //            ProductColumn.PIC_SMALL_URL,
        //            ProductColumn.PRICE,
        //            ProductColumn.PRODUCT_NAME, 
        //            ProductColumn.PRODUCT_RATING,
        //            ProductColumn.RELATE_FREE_SHIPPING,
        //            ProductColumn.REVIEW_COUNT,
        //            ProductColumn.SKU,
        //            ProductColumn.SPECIFICATION, 
        //            ProductColumn.TYPE,
        //            ProductColumn.UPDATE_TIME, 
        //            ProductColumn.WEB_URL }; 19
        
        ProductModel model = new ProductModel();
        model.setCurrencyCode(c.getString(0));
        model.setEntityID(c.getInt(1));
        model.setFreeShipping(c.getInt(2));
        model.setIntroduction(c.getString(3));
        model.setLanguage(c.getString(4));
        model.setListprice(c.getFloat(5));
        model.setPhotosCount(c.getInt(6));
        model.setBigPictureURL(readArrayStream(c.getBlob(7)));
        model.setMediumPictureURL(readArrayStream(c.getBlob(8)));
        model.setSmallPictureURL(readArrayStream(c.getBlob(9)));
        model.setPrice(c.getFloat(10));
        model.setShortHeadLine1(c.getString(11));
        model.setProductRating(c.getFloat(12));
        model.setRelateFreeShipping(readArrayStream(c.getBlob(13)));
        model.setReviewCount(c.getInt(14));
        model.setSku(c.getInt(15));
        model.setSpec(c.getString(16));
        //跳过 Type 读取略，作为分类条件 
        model.setCacheUpdateTime(c.getLong(18));
        model.setWebUrl(c.getString(19));
        return model;
    }
    
    // 解析产品列表
    private ArrayList<ProductModel> parseModelList(Cursor c)
    {
        if (Logger.isLog)
        {
            Logger.d("parseModelList(Cursor) - start");
        }
        
        if (null == c || c.getCount() < 1)
        {
            if (Logger.isLog)
            {
                Logger.d("parseModelList(Cursor) - end");
            }
            return null;
        }
        
        c.moveToFirst();
        
        if (Logger.isLog)
        {
            Logger.i("parseModelList(Cursor) - count: " + c.getCount());
        }
        
        ArrayList<ProductModel> result = new ArrayList<ProductModel>(c.getCount());
        
        do
        {
            result.add(getSingleModel(c));
            
        } while (c.moveToNext());
        
        if (Logger.isLog)
        {
            Logger.d("parseModelList(Cursor) - end");
        }
        return result;
    }
    
    private static byte[] writeStream(String[] input)
    {
        ByteArrayOutputStream byteOutput = null;
        
        ObjectOutputStream output = null;
        
        byte[] result = null;
        
        try
        {
            byteOutput = new ByteArrayOutputStream(input.length * 256);
            
            output = new ObjectOutputStream(byteOutput);
            
            output.writeObject(input);
            
            result = byteOutput.toByteArray();
            
        }
        catch (Exception e)
        {
            Logger.w(TAG, "writeStream error.", e);
        }
        finally
        {
            
            if (null != output)
            {
                try
                {
                    output.close();
                    
                }
                catch (IOException e)
                {
                    Logger.w(TAG, "writeStream error.", e);
                }
            }
            if (null != byteOutput)
            {
                try
                {
                    byteOutput.close();
                }
                catch (IOException e)
                {
                    Logger.w(TAG, "writeStream error.", e);
                }
            }
        }
        
        return result;
    }
    
    private static String[] readArrayStream(byte[] inputByte)
    {
        
        if (null == inputByte || inputByte.length < 1)
        {
            return null;
        }
        
        ByteArrayInputStream byteInput = null;
        
        ObjectInputStream input = null;
        
        Object obj = null;
        
        try
        {
            byteInput = new ByteArrayInputStream(inputByte);
            
            input = new ObjectInputStream(byteInput);
            
            obj = input.readObject();
            
        }
        catch (Exception e)
        {
            Logger.w(TAG, "readArrayStream error.", e);
        }
        finally
        {
            if (null != input)
            {
                try
                {
                    input.close();
                }
                catch (IOException e)
                {
                    Logger.w(TAG, "readArrayStream error.", e);
                }
            }
            if (null != byteInput)
            {
                try
                {
                    byteInput.close();
                }
                catch (IOException e)
                {
                    Logger.w(TAG, "readArrayStream error.", e);
                }
            }
        }
        
        return (obj instanceof String[] ? (String[])obj : null);
    }
}
